package sf01.studentmngmsystem.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import sf01.studentmngmsystem.entity.Student;
import sf01.studentmngmsystem.service.StudentService;
import jakarta.servlet.http.HttpSession;

@Controller
public class PageController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/students")
    public String students() {
        return "students";
    }

    @GetMapping("/student/profile")
    public String studentProfile(@RequestParam Long id, HttpSession session, Model model) {
        // 检查是否已登录（学生或教师）
        if (session.getAttribute("student") == null && session.getAttribute("teacher") == null) {
            return "redirect:/login";
        }
        
        try {
            // 获取学生信息
            Student student = studentService.getStudentById(id);
            if (student != null) {
                // 将学生信息传递给模板
                model.addAttribute("student", student);
                
                // 检查是否有管理员权限（教师登录）
                boolean hasAdminPermission = session.getAttribute("teacher") != null;
                model.addAttribute("hasAdminPermission", hasAdminPermission);
                
                return "student-profile";
            } else {
                // 学生不存在，重定向到登录页
                return "redirect:/login";
            }
        } catch (Exception e) {
            // 发生错误，重定向到登录页
            return "redirect:/login";
        }
    }
}
